﻿using BulkUploadGovernanceFiles.Repositories;
using System;
using System.Collections.Generic;
using System.IO;

using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using BulkUploadGovernanceFiles.Models;

namespace BulkUploadGovernanceFiles.MoveInsightToS3Buckets
{
    public class ProcessInsights
    {
        private string _statusMessage;

        public string StatusMessage
        {
            get { return _statusMessage; }
        }

        public int NumberOfFiles { get { return _insights.Count(); } }
        private readonly IEnumerable<Insight> _insights;
        private readonly InsightRepository _insightsRepository;
        private readonly MongoGridFSRepository _gridFsRepository;

        private readonly IFileUpload _fileUpload;

        public ProcessInsights(InsightRepository insightsRepository, MongoGridFSRepository gridFsRepository, IFileUpload fileUpload)
        {
            _insightsRepository = insightsRepository;
            _statusMessage = "";
            _gridFsRepository = gridFsRepository;
            _fileUpload = fileUpload;
            _insights = _insightsRepository.FindAll();
        }
        private async Task ProcessFiles(CancellationToken token, IProgress<int> progress)
        {
            await Task.Run(() =>
            {
                var i = 0;
                foreach (var insight in _insights)
                {
                    ProcessInsight(insight.Id, insight.FileId,  "FileS3Name");
                    ProcessInsight(insight.Id, insight.ImageId, "ImageS3Name");
                    progress.Report(++i);
                }
                _statusMessage = "Done";
            }, token);
        }

        private async void ProcessInsight(Guid id, Guid fileId, string fieldName)
        {
            var fileStream = _gridFsRepository.ReadStreamFromMongoFs(fileId);
            if (fileStream != null)
            {
                var fileIdentifier = fileId + "_" + fileStream.Item2;
                await _fileUpload.UploadAsynk(fileIdentifier, fileStream.Item1);
                _insightsRepository.Update(id, fieldName, fileIdentifier);
            }
        }

        public async Task Process(CancellationToken token, IProgress<int> progress)
        {
            try
            {
                await ProcessFiles(token, progress);
            }
            catch (OperationCanceledException ex)
            {
                _statusMessage = "Operation canceled !";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
